<template>
  <div class="loginDialog">
    <el-dialog v-model="showLogin" :show-close="false" class="dialogBody" :before-close="closeLogin" close-on-press-escape destroy-on-close draggable>
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <el-tabs v-model="activeNav" class="headerTabs" @tab-click="handleNav">
            <el-tab-pane :label="t('login.memberLogin')" name="login"></el-tab-pane>
            <el-tab-pane :label="t('login.oneRegister')" name="register"></el-tab-pane>
            <el-tab-pane :label="t('login.forgetPwd')" name="forget"></el-tab-pane>
          </el-tabs>

          <el-button class="headerClose" type="warning" circle @click="close">
            <el-icon ><div class="iconfont icon guanbi"></div></el-icon>
          </el-button>

        </div>
      </template>
      <div class="dialogBody">
        <div class="loginBody" v-if="activeNav=='login'">
          <el-form
            ref="loginFormRef"
            style="max-width: 600px"
            :model="loginForm"
            :rules="loginRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="t('login.mobile')+'：'"
              prop="mobile"
            >
              <el-input
                v-model.number="loginForm.mobile"
                type="text"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.pwd')+'：'"
              prop="password"
            >
              <el-input
                v-model="loginForm.password"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.captchaCode')+'：'"
              prop="imgCode"
            >
              <el-input class="imgCodeBox"
                v-model="loginForm.imgCode"
                type="text"
                autocomplete="off"
              >
                <template #append>
                  <el-image id="image-code" style="width: 150px; height: 50px" alt="验证码" fit="contain" v-on:click="loadImageCode()" />
                  <!-- <img id="image-code" alt="验证码" v-on:click="loadImageCode()" /> -->
                </template>
              </el-input>
            </el-form-item>

            <el-form-item v-if="showNewReg">
                <el-divider content-position="right">{{ newRegToast }}</el-divider>
            </el-form-item>
            
          </el-form>
        </div>
        <div class="registerBody" v-if="activeNav=='register'">
          <el-form
            ref="regFormRef"
            style="max-width: 600px"
            :model="regForm"
            :rules="regRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="t('login.mobile')+'：'"
              prop="mobile"
            >
              <el-input
                v-model.number="regForm.mobile"
                type="text"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.nickName')+'：'"
              prop="nickName"
            >
              <el-input
                v-model="regForm.nickName"
                type="text"
                autocomplete="off"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="forgetBody" v-if="activeNav=='forget'">
          <el-form
            ref="forgetFormRef"
            style="max-width: 600px"
            :model="forgetForm"
            :rules="forgetRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="t('login.mobile')+'：'"
              prop="mobile"
            >
              <el-input
                v-model.number="forgetForm.mobile"
                type="text"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.smsCode')+'：'"
              prop="shortMessageCode"
            >
              <el-input
                v-model="forgetForm.shortMessageCode"
                type="text"
                autocomplete="off"
              >
                <template #append>
                  <el-button @click="SMSTime(true)" :disabled="btnText!='发送短信验证码' && btnText!='Send Message Code'?true:false">{{ btnText }}</el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item
              :label="t('login.pwd')+'：'"
              prop="passwordOriginal"
            >
              <el-input
                v-model="forgetForm.passwordOriginal"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.pwdConf')+'：'"
              prop="passwordConfirm"
            >
              <el-input
                v-model="forgetForm.passwordConfirm"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeLogin">{{ t('login.cancle') }}</el-button>
          <el-button @click="resetData(activeNav=='login'?loginFormRef:(activeNav=='register')?regFormRef:forgetFormRef)">{{ t('login.reset') }}</el-button>
          <el-button type="primary" @click="submitData(activeNav=='login'?loginFormRef:(activeNav=='register')?regFormRef:forgetFormRef,activeNav)">
            {{ activeNav=='login'?t('login.memberLogin'):(activeNav=='register'?t('login.oneRegister'):(activeNav=='forget'?t('login.submit'):t('login.submit'))) }}
          </el-button>
        </div>
      </template>
      
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
//全局调用$message
const { proxy }: any = getCurrentInstance()
import { throwError } from 'element-plus/es/utils/error.mjs';
// import api from '@/api/index.ts'
import { watch } from 'vue';

//引入国际化
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

//引入router跳转
const router=useRouter()

const $emit=defineEmits<{
  (e:String,value:any):void
}>()

//监听
const props = defineProps({
  language: {
      type: String,
      default: 'zh'
  },
 
})
watch(() => proxy.language, (newVal, oldVal) => {
  // console.log("newVal", newVal)
  // console.log("oldVal", oldVal)
  // console.log("languag",props.language)
  
},{ immediate: true, deep: true })

// watch(()=>loginForm,(newVal,oldVal)=>{
//   console.log("loginForm: ",newVal)
// }, { immediate: true, deep: true })

const showLogin=ref(false)
//标签页
const activeNav=ref('login')

/***************引入组件变量*******start*******/

import useForm from '@/entity/login/useForm';
const {titleId,
    titleClass,
    localUser,
    loginForm,
    loginFormRef,
    loginRules,
    regForm,
    regFormRef,
    regRules,
    forgetForm,
    forgetFormRef,
    forgetRules,
    sendSMForm,
    sendSMFormRef,
    sendSMRules
  }= useForm(t)
import useMethods from '@/entity/login/useMethods';

const {resetData,submitData,login,register,getCodeToken}
=useMethods(t,{loginForm,regForm,forgetForm,showLogin},router)

/***************引入组件变量*****end********/

function initLogin(e:any){
  console.log("打开登录框：",e)
  if(e){
    activeNav.value==e
    activeNavChange(e)
  }
  console.log("activeNav: ",activeNav.value)
  
  showLogin.value=true
  loadImageCode()
  keydownEvent("add")
}

function closeLogin(){
  console.log("进入关闭")
  keydownRemoveEvent("remove")
  showLogin.value=false
}

//监听键盘事件
function handleEnterEvent(e:any){
  // console.log("键盘事件：",e,e.code)
  if(e.code=='Enter' || e.code=='NumpadEnter'){
    console.log("回车事件：",e)
    // submitData(activeNav.value=='login'?loginFormRef:(activeNav.value=='register')?regFormRef:forgetFormRef,activeNav)
  }
}

const keydownEvent=(e:any)=>{
  document.addEventListener('keydown',handleEnterEvent)
}

const keydownRemoveEvent=(e:any)=>{
  document.removeEventListener('keydown',handleEnterEvent)
}

let showNewReg:boolean=false
const newRegToast='新注册会员默认密码，请联系客服：0991-6232202'

function handleNav(e:any){
  // console.log("当前nav：",e.props.name)
  activeNav.value=e.props.name
  if(activeNav.value=='login'){
    loadImageCode()
  }
  // console.log("当前nav：",e.props.name,"activeNav: ",activeNav.value)
  
}

function activeNavChange(e:any){
  activeNav.value=e
  console.log("当前nav：",e,"activeNav: ",activeNav.value)
}

function loadImageCode(){
  setTimeout(()=>{
    console.log("加载图片验证码",document.getElementById('image-code'))
    document.getElementById('image-code')?.setAttribute('src','http://39.104.21.39:8899/business/client/kaptcha/image-code/'+getCodeToken())
  },)
  
}


/**********忘记密码表单*******/

let countDown=61
const btnText=ref(props.language=='zh'?'发送短信验证码':'Send Message Code')
let timer:any={}
const SMSTime=async (flag:any)=>{
  // console.log("forgeForm: ",forgetForm.shortMessageCode)
  try{
    //form表单全部
    // const valid=await forgetFormRef.value?.validate()
    //指定参数校验
    const valid=await forgetFormRef.value?.validateField('mobile')
    // console.log("valid: ",valid)
    if(valid){
      // console.log("通过")
      if(flag){
        countDown=60
        clearTimeout(timer)
      }
      // console.log('countDown-------',countDown)
      if(countDown==0 || countDown==61){
        btnText.value=props.language=='zh'?'发送短信验证码':'Send Message Code'
        return
      }else{
        countDown--
        btnText.value=countDown+ (props.language=='zh'?' 后重新获取':' Seconds Retrieve It')
      }
      // console.log("btnText: ",btnText)
      timer= setTimeout(()=>{
        SMSTime(false)
      },1000)
    }
  }catch(error){
    console.log("验证手机号异常：",error)
  }
  
}

//向父组件暴露方法
defineExpose({
  initLogin,
  closeLogin
})

/*******************other********************/

let productTypes: any = ref([])

//使用api调用
const {data,error,status,refresh}= await GetProductCats()

  // console.log("stats: ",status.value)
  // console.log("refresh: ",refresh)
  // console.log("分类响应：", data.value)
  // console.log("error: ", error.value?.data,error.value?.data.error+': '+error.value?.data.status+'! 错误页面：'+error.value?.data.path)

  
  if(process.server && error.value){

    throwError((error.value?.data,error.value?.data.error+': '+error.value?.data.status),'页面加载失败，请联系客服！')
  }
  
  if(data.value?.length>0){
    // productTypes.value = data.value
    // $emit('productTypesChange',productTypes.value)
    
  }
//跳转产品
function toProduct(item:any){
  // console.log("去产品页：",item)
  navigateTo({
    path: '/product/list/1',
    // query: {
    //   id: item.id
    // }
  })

}



</script>

<style lang="scss" scoped>
@import '@/assets/css/common.scss';
@import '@/assets/css/index.scss';

:deep(.el-dialog){
    width: 600px !important;
  }

.loginDialog{
  
  .imgCodeBox{
    :deep(.el-input-group__append){
      width: 125px;
      height: 50px;
      padding: 0 !important;
    }
    .image-code{
      cursor: pointer;
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
  
}
.my-header{
  width:100%;
  display: flex;
  .headerTabs{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    :deep(.el-tabs__header){
      width: 100%;
      display:flex;
    }
    :deep(.el-tabs__nav-wrap){
      width: 100%;
      display:flex;
    }
    :deep(.el-tabs__item){
      font-size: 18px;
    }
    :deep(.is-active){
      font-weight: 700;
    }
  }
  .headerClose{
    position: absolute;
    right: 15px;
    top: 15px;
  }
  
}
</style>